import { chunk, omit } from 'lodash';

type TNewRecord = {
  devices: Record<string, any>[];
  [key: string]: any;
};

export function transformStatisticMultiObjectResponse(
  res: {
    data: {
      total?: number;
      records: Record<string, any>[];
    };
  },
  params: {
    codes: string[];
  } & API.PageParams,
  keysToMap: string[],
) {
  const newTotal = Math.ceil((res.data?.total ?? 0) / params.codes.length);
  // 将records按照对象数量进行chunk分组
  const newRecords = chunk(res.data?.records, params.codes.length).map((chunk) => {
    const newRecordItem: {
      devices: Record<string, any>[];
      [key: string]: any;
    } = {
      devices: [],
      ...omit(chunk[0], keysToMap),
    };

    return chunk
      .sort((a, b) => (a.deviceName ?? '').localeCompare(b.deviceName ?? ''))
      .reduce<TNewRecord>((acc, cur, index) => {
        acc.devices.push(cur);
        keysToMap.forEach((key) => {
          acc[`${key}${index + 1}`] = cur[key];
        });
        return acc;
      }, newRecordItem);
  });

  const newRes = {
    ...res,
    data: {
      ...res.data,
      total: newTotal,
      records: newRecords,
      pageSize: params.pageSize!,
    },
  };

  return newRes;
}

/**
 * 数组根据日期和areaId转为列
 * @param arr
 */
export function rowToColumns(arr: any[]) {
  // 使用一个对象来存储日期和对应的分区数据
  const resultMap: Record<string, Record<string, any>> = {};

  arr.forEach((item) => {
    const {
      date,
      areaName,
      chargeCapacity,
      dischargeCapacity,
      emsChargeCapacity,
      emsDischargeCapacity,
      income,
      reportId,
      stationId,
      stationName,
    } = item;

    // 如果 date 不存在，初始化
    if (!resultMap[date]) {
      resultMap[date] = {
        date: date,
        reportId,
        stationId,
        stationName,
      };
    }

    // 使用 areaName 作为前缀，构造新的字段名
    const areaPrefix = areaName;
    resultMap[date][`${areaPrefix}_chargeCapacity`] = chargeCapacity;
    resultMap[date][`${areaPrefix}_dischargeCapacity`] = dischargeCapacity;
    resultMap[date][`${areaPrefix}_emsChargeCapacity`] = emsChargeCapacity;
    resultMap[date][`${areaPrefix}_emsDischargeCapacity`] = emsDischargeCapacity;
    resultMap[date][`${areaPrefix}_income`] = income;
  });

  // 将对象转换为数组
  return Object.values(resultMap);
}
